package main

import "fmt"

func shiftGrid(grid [][]int, k int) [][]int {
	M, N := len(grid), len(grid[0])
	k = k % (M * N)

	res := make([][]int, M)
	for i := 0; i < M; i++ {
		res[i] = make([]int, N)
	}

	for i := 0; i < M; i++ {
		for j := 0; j < N; j++ {
			sX, sY := getSrcXy(i, j, M, N, k)
			res[i][j] = grid[sX][sY]
		}
	}
	return res
}

func getSrcXy(i, j int, M, N int, k int) (int, int) {
	tar := i*N + j
	src := (tar - k + M*N) % (M * N)
	fmt.Println(tar, src)
	return src / N, src % N
}

func main() {
	//M, N := 3, 3
	//var i, j, k int
	//i, j = 2, 2
	//k = 1
	//fmt.Println(getSrcXy(i, j, M, N, k))

	grid := [][]int{{1}, {2}, {3}, {4}, {7}, {6}, {5}}
	k := 23
	res := shiftGrid(grid, k)
	fmt.Println(res)
}
